<template>
  <div class="d-flex-c full-box">
    <div
      class="operation-panel p-h-s"
      v-show="expanded"
    >
      <div class="flex-between m-b-mini">
        <el-tag
          v-if="targetPosition.length"
          closable
          @close="closeTag"
        >
          <span
            class="m-b-mini"
            v-if="!targetName"
          >目标坐标：{{ `Ⓔ ${$helper.formatDegree(targetPosition[0])} Ⓝ ${$helper.formatDegree(targetPosition[1])}` }}</span>
          <span v-else>{{ targetName }}</span>
        </el-tag>
        <div v-else />
        <el-button
          size="mini"
          type="primary"
          plain
          @click="openRecords"
        >
          已保存信息
        </el-button>
      </div>
      <el-form
        size="mini"
        :model="formData"
        :rules="rules"
        label-width="80px"
        ref="form"
      >
        <el-form-item
          label="雨量"
          prop="YL"
        >
          <BKInput
            v-model="formData.YL"
            size="mini"
            is-number
            class="has-unit"
            :digits="2"
          >
            <template slot="append">
              mm
            </template>
          </BKInput>
        </el-form-item>
        <el-form-item
          label="历时"
          prop="LS"
        >
          <RadioButton
            v-model="formData.LS"
            dictionary-key="YSQJC_JC_BYTJBZLS2"
          >
            <!-- <template #append>
              <el-button
                size="mini"
                v-show="formData.LS"
                @click="openStandardModal"
              >
                选择标准历时点位
              </el-button>
            </template> -->
          </RadioButton>
        </el-form-item>
        <div
          class="ls-row"
          v-show="otherLs.includes(formData.LS)"
        >
          <div class="label">
            上一历时
          </div>
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="Ht"
                prop="HTA"
              >
                <BKInput
                  v-model="formData.HTA"
                  size="mini"
                  is-number
                  class="has-unit"
                  :digits="2"
                >
                  <template slot="append">
                    mm
                  </template>
                </BKInput>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="Cv"
                prop="CVA"
              >
                <BKInput
                  v-model="formData.CVA"
                  size="mini"
                  is-number
                  :digits="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          class="ls-row"
          v-show="otherLs.includes(formData.LS)"
        >
          <div class="label">
            下一历时
          </div>
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="Ht"
                prop="HTB"
              >
                <BKInput
                  v-model="formData.HTB"
                  size="mini"
                  is-number
                  :digits="2"
                  class="has-unit"
                >
                  <template slot="append">
                    mm
                  </template>
                </BKInput>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="Cv"
                prop="CVB"
              >
                <BKInput
                  v-model="formData.CVB"
                  size="mini"
                  is-number
                  :digits="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row v-show="!otherLs.includes(formData.LS)">
          <el-col :span="14">
            <el-form-item
              label="Ht"
              prop="HTA"
            >
              <BKInput
                v-model="formData.HTA"
                size="mini"
                is-number
                :digits="2"
              >
                <template slot="append">
                  mm
                </template>
              </BKInput>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="Cv"
              prop="CVA"
            >
              <BKInput
                v-model="formData.CVA"
                size="mini"
                is-number
                :digits="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="分区名称"
          prop="FQMC"
        >
          <BKSelect
            v-model="formData.FQMC"
            dictionary-key="ysqjc_jc_fqmc"
            class="full-width"
          />
        </el-form-item>
        <el-form-item
          label="面积km²"
          prop="MJ"
        >
          <!-- <RadioButton
            v-model="formData.MJLX"
            dictionary-key="ysqjc_jc_bytjmj"
          /> -->
          <BKInput
            is-number
            v-model="formData.MJ"
            :digits="2"
            size="mini"
          />
        </el-form-item>
      </el-form>
      <div class="buttons d-flex ai-c jc-c">
        <el-button
          size="mini"
          type="primary"
          @click="getParams"
          plain
        >
          获取计算参数
        </el-button>
        <el-button
          size="mini"
          type="primary"
          @click="calculate"
          :disabled="!targetPosition.length"
        >
          计算
        </el-button>
        <el-button
          size="mini"
          type="primary"
          @click="calculateAndSave"
          :disabled="!targetPosition.length"
        >
          计算并保存
        </el-button>
      </div>
    </div>
    <div class="p-h-mini">
      <el-divider>
        <div
          class="split-icon"
          @click="expanded = !expanded"
        >
          <i class="el-icon-arrow-down" />
          <i class="el-icon-arrow-up" />
        </div>
      </el-divider>
    </div>
    <div class="flex-1 overflow-hidden">
      <BKTable
        ref="grid"
        :has-add="false"
        :has-batch-remove="false"
        :toolbar-config="null"
        :has-pager="false"
        style="padding-top: 0;"
        :has-checkbox="false"
        :columns="columns"
        :data="tableData"
        class="p-a-mini"
        :row-class-name="rowClassName"
      >
        <template #toolbarLeft>
          <div
            class="full-box flex-between f-16"
            style="margin-bottom: 4px;"
          >
            <span v-show="cxq">重现期 <span
              style="color: #49c398;"
              class="f-w"
            >{{ cxq }}</span> 年</span>
            <span v-show="!cxq" />
            <el-button
              size="mini"
              type="primary"
              plain
              @click="exportData"
              :loading="exportLoading"
            >
              导出
            </el-button>
          </div>
        </template>
      </BKTable>
    </div>
    <SaveRecords
      ref="records"
      meta-set="YSQJC_BYTJ_MYLCXQ"
      id-key="MYLID"
      @change="clickSaveInfo"
    />
    <BKModal
      v-model="visible"
      title="标准历时点位"
      width="1200px"
      height="600px"
      transfer
    >
      <BKTable
        :columns="pointsColumns"
        :data="pointsData"
        :has-pager="false"
        class="p-a-mini"
      />
    </BKModal>
  </div>
</template>

<script>
import SaveRecords from '../save-records.vue'
import RadioButton from '../radio-button.vue'
export default {
  name: 'AreaTabPanel',
  components: { SaveRecords, RadioButton },
  data () {
    return {
      formData: {
        YL: '',
        LS: '3',
        HTA: '',
        CVA: '',
        HTB: '',
        CVB: '',
        FQMC: '',
        MJ: ''
      },
      expanded: true,
      columns: [
        { title: '历时', field: 'LS_TEXT', minWidth: 65 },
        { title: '年一遇', field: 'NYY', minWidth: 70 },
        {
          title: '频率',
          field: 'PL',
          minWidth: 70,
          slots: {
            header: () => {
              return [
                <div class="d-flex-c ai-c">
                  <span>频率</span>
                  <span>{'（%）'}</span>
                </div>
              ]
            }
          }
        },
        { title: 'ap', minWidth: 60, field: 'AP', formatter: ({ cellValue }) => cellValue.toFixed(3) },
        {
          field: 'HTP',
          minWidth: 80,
          slots: {
            header: () => {
              return [
                <div class="d-flex-c ai-c">
                  <span>H点p,t</span>
                  <span>{'(mm)'}</span>
                </div>
              ]
            }
          },
          formatter: ({ cellValue }) => cellValue.toFixed(1)
        },
        {
          field: 'HPT',
          minWidth: 80,
          slots: {
            header: () => {
              return [
                <div class="d-flex-c ai-c">
                  <span>H面p,t</span>
                  <span>{'(mm)'}</span>
                </div>
              ]
            }
          },
          formatter: ({ cellValue }) => cellValue.toFixed(1)
        }
      ],
      tableData: [],
      cxq: '',
      unit: 'min',
      unitList: [
        { label: 'min', value: '1' },
        { label: 'h', value: '2' },
        { label: 'd', value: '3' }
      ],
      otherLs: ['2', '4', '6'],
      pointsData: [],
      visible: false,
      exportLoading: false,
      targetPosition: [],
      targetName: '',
      targetId: ''
    }
  },
  computed: {
    pointsColumns () {
      if (this.otherLs.includes(this.formData.LS)) {
        return [
          { title: '经度', field: 'JD', width: 110 },
          { title: '纬度', field: 'WD', width: 110 },
          {
            title: '上一历时',
            children: [
              { title: '创建时间', field: 'TIMEA', width: 175 },
              { title: '历时', field: 'LSA_TEXT' },
              { title: 'Ht', field: 'HTA' },
              { title: 'Cv', field: 'CVA' }

            ]
          },
          {
            title: '下一历时',
            children: [
              { title: '创建时间', field: 'TIMEB', width: 175 },
              { title: '历时', field: 'LSB_TEXT' },
              { title: 'Ht', field: 'HTB' },
              { title: 'Cv', field: 'CVB' }

            ]
          },
          {
            title: '操作',
            slots: {
              default: ({ row }) => {
                return [
                  <el-button size="mini" type="primary" onClick={() => this.choose(row)}>选择</el-button>
                ]
              }
            }
          }
        ]
      } else {
        return [
          { title: '经度', field: 'JD', width: 110 },
          { title: '纬度', field: 'WD', width: 110 },
          { title: '创建时间', field: 'TIMEA', width: 175 },
          { title: '历时', field: 'LSA_TEXT' },
          { title: 'Ht', field: 'HTA' },
          { title: 'Cv', field: 'CVA' },
          {
            title: '操作',
            slots: {
              default: ({ row }) => {
                return [
                  <el-button size="mini" type="primary" onClick={() => this.choose(row)}>选择</el-button>
                ]
              }
            }
          }
        ]
      }
    },
    rules () {
      if (this.otherLs.includes(this.formData.LS)) {
        return {
          YL: [{ required: true, message: '请填写雨量' }],
          LS: [{ required: true, message: '请选择历时' }],
          HTA: [{ required: true, message: '请填写Ht' }],
          CVA: [{ required: true, message: '请填写Cv' }],
          HTB: [{ required: true, message: '请填写Ht' }],
          CVB: [{ required: true, message: '请填写Cv' }],
          FQMC: [{ required: true, message: '请选择分区名称' }],
          MJ: this.formData.FQMC === '1' ? [{ required: true, message: '请输入面积' }, { type: 'number', min: 0, max: 1500, message: '请输入0-1500的数字', trigger: 'none' }] : [{ required: true, message: '请输入面积' }, { type: 'number', min: 0, max: 2000, message: '请输入0-2000的数字', trigger: 'none' }]
        }
      } else {
        return {
          YL: [{ required: true, message: '请填写雨量' }],
          LS: [{ required: true, message: '请选择历时' }],
          HTA: [{ required: true, message: '请填写Ht' }],
          CVA: [{ required: true, message: '请填写Cv' }],
          FQMC: [{ required: true, message: '请选择分区名称' }],
          MJ: this.formData.FQMC === '1' ? [{ required: true, message: '请输入面积' }, { type: 'number', min: 0, max: 1500, message: '请输入0-1500的数字', trigger: 'none' }] : [{ required: true, message: '请输入面积' }, { type: 'number', min: 0, max: 2000, message: '请输入0-2000的数字', trigger: 'none' }]
        }
      }
    }
  },
  methods: {
    rowClassName ({ row }) {
      if (row.BH === '1') {
        return 'c-red'
      } else {
        return ''
      }
    },
    async calculate () {
      const v = await this.$refs.form.validate()
      if (v) {
        if (this.formData.FQMC === '1' && Number(this.formData.MJ) > 1500) {
          this.$message.warning('暂无此面积范围的成果数据')
          return
        }
        const params = this.otherLs.includes(this.formData.LS) ? {
          yl: this.formData.YL,
          ls: this.formData.LS,
          mj: this.formData.MJ,
          fq: this.formData.FQMC,
          hta: this.formData.HTA,
          cva: this.formData.CVA,
          htb: this.formData.HTB,
          cvb: this.formData.CVB
        } : {
          yl: this.formData.YL,
          ls: this.formData.LS,
          mj: this.formData.MJ,
          fq: this.formData.FQMC,
          ht: this.formData.HTA,
          cv: this.formData.CVA
        }

        const { cxq, gcdata } = await this.$request.post('/ysjc/bytjjs/getmylCxqJsgc', params)
        this.cxq = cxq
        this.tableData = gcdata
      }
    },
    async calculateAndSave () {
      await this.calculate()
      this.$request.post('/ysjc/bytjjs/saveMylcg', {
        gnq: { ...this.formData, CXQ: this.cxq, JD: this.targetPosition[0], WD: this.targetPosition[1], STCD: this.targetId },
        gcb: this.tableData
      })
      this.$message.success('操作成功')
    },
    openRecords () {
      this.$refs.records.open()
    },
    async clickSaveInfo (row) {
      this.formData = row
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_BYTJ_MYLJSGC',
        methodCode: 'selectJsGc',
        methodParams: { MYLID: row.MYLID }
      })
      this.cxq = row.CXQ
      this.tableData = rows
      this.targetPosition = [row.JD, row.WD]
      this.setPosition({ coordinate: this.targetPosition, name: row.STCD ? `${row.STNM} ${row.STCD}` : '', id: row.STCD })
    },
    async exportData () {
      this.exportLoading = true
      const { data, fileName } = await this.$request.getFileStreamByPost('ysjc/bytjjs/exportNew', {
        table_name: 'YSQJC_BYTJ_MYLSCXQJSGC',
        data: this.tableData.map((item, i) => ({
          XH: i + 1,
          HTP: item.HTP,
          LS: item.LS_TEXT,
          PL: item.PL,
          NYY: item.NYY,
          AP: item.AP,
          HPT: item.HPT,
          BH: item.BH
        }))
      })
      this.$request.downloadBlobFile(data, fileName)
      this.exportLoading = false
    },
    async openStandardModal () {
      const data = await this.$request.post('/ysjc/bytjjs/getMylOtherData', { ls: this.formData.LS })
      this.pointsData = data
      this.visible = true
    },
    async choose (row) {
      const layer = await this.$mapManager.invokeUtils('getLayer', 'showinglayer')
      layer.getSource().clear()
      const point = this.$mapManager.getMapComponent().map1.bkol.getPoint(row.JD, row.WD)
      const feature = new window.ol.Feature(point)
      layer.getSource().addFeature(feature)
      this.formData.HTA = row.HTA || ''
      this.formData.CVA = row.CVA || ''
      this.formData.HTB = row.HTB || ''
      this.formData.CVB = row.CVB || ''
      if ((!row.HTB || !row.HTA) && this.otherLs.includes(this.formData.LS)) {
        const result = await this.$mapManager.invoke('transfromFeature', feature, false)
        const { ht, cv, msg } = await this.$request.post('/ysjc/bytjjs/getpitcvht', { point: result, ht: !row.HTA ? row.LSALX : row.LSBLX })
        this.formData[!row.HTA ? 'HTA' : 'HTB'] = ht || ''
        this.formData[!row.HTA ? 'CVA' : 'CVB'] = cv || ''
        this.$message.warning(`本次选择的点位缺少${!row.HTA ? '上' : '下'}一历时的数据，已自动计算完成${msg ? ',' + msg : ''}`)
      }
      if (!row.HTA && !this.otherLs.includes(this.formData.LS)) {
        this.$message.warning('本次选择的点位缺少标准历时的数据，请在标准历时点雨量模块操作计算')
      }
      this.visible = false
    },
    async setPosition ({ coordinate, name, id }) {
      const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
      layer.getSource().clear()
      this.targetPosition = coordinate
      this.targetName = name || ''
      this.targetId = id || ''

      const feature = new window.ol.Feature(new window.ol.geom.Point(coordinate))
      feature.setStyle(new window.ol.style.Style({
        image: new window.ol.style.Circle({
          radius: 6,
          fill: new window.ol.style.Fill({
            color: '#ffff'
          }),
          stroke: new window.ol.style.Stroke({
            color: '#00dc10',
            width: 2
          })
        })
      }))
      layer.getSource().addFeature(feature)
    },
    async getParams () {
      if (!this.targetPosition.length) {
        this.$message.warning('请在地图点选或者选择一个站点')
        return
      }
      if (!this.formData.LS) {
        this.$message.warning('请选择历时')
        return
      }
      this.getHtAndCvByPosition(this.targetPosition)
    },
    closeTag () {
      this.targetPosition = []
      this.targetName = ''
      this.$mapManager.invoke('clearLayers', ['graphicLayer', 'modifylayer'])
    },
    async getHtAndCvByPosition (coordinate) {
      const feature = new window.ol.Feature(new window.ol.geom.Point(coordinate))
      const wkt = await this.$mapManager.invoke('transfromFeature', feature, false)
      const { HTA, HTB, CVA, CVB, msg } = await this.$request.post('/ysjc/bytjjs/getLspitcvht', { point: wkt, ls: this.formData.LS })
      this.formData.CVA = CVA || ''
      this.formData.HTA = HTA || ''
      this.formData.CVB = CVB || ''
      this.formData.HTB = HTB || ''
      if (msg) {
        this.$message.warning(msg)
      } else {
        this.$message.success('获取数据成功')
      }
    }
  },
  created () {
    this.$mapManager.addEventListener('mapModifyEnd-pick', this.setPosition)
    this.$root.$on('mapPick', this.setPosition)
  },
  beforeDestroy () {
    this.$mapManager.removeEventListener('mapModifyEnd-pick', this.setPosition)
    this.$root.$off('mapPick', this.setPosition)
  }
}
</script>

<style lang="scss" scoped>
.ls-row {
  .label {
    width: 60px;
    float: left;
    line-height: 28px;
    font-size: 14px;
  }

  > .el-row {
    margin-left: 60px;
  }
}

::v-deep .has-unit .el-input-group__append {
  padding: 0 10px;
}

::v-deep .has-select .el-input-group__append {
  width: 80px;
}

.split-icon {
  position: relative;
  width: 20px;
  height: 22px;
  cursor: pointer;

  > i {
    position: absolute;

    &:first-child {
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }

    &:last-child {
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  &:hover {
    > i {
      color: #063ab6;
      font-weight: bold;
    }
  }
}

::v-deep .el-divider__text {
  padding: 0 10px;
}

::v-deep .el-divider--horizontal {
  margin: 20px 0 10px;
}

::v-deep .el-dropdown__caret-button {
  height: 28px;
}

::v-deep .radio-button-container .radio-button-item {
  width: 61.8px;
}
</style>
